package com.it.data_linkedList.leetcode;

import com.it.data_tree.util.ColorPrintln;

/**
 * @author: Coke
 * @DateTime: 2023/06/10/17:49
 * 检测表是否右环 并检测出 入门
 **/
public class E08Leetcode141 {
    
    /**
     * 检测表是否右环
     *
     * @param head:
     * @return boolean
     * @DateTime: 2023/6/10 20:06
     * @author: Coke
     */
    public static boolean hasCycle (ListNode head) {
        ListNode t = head; // 兔
        ListNode g = head; // 龟
        while (t != null && t.next != null) {
            g = g.next;
            t = t.next.next;
            if (g == t) {
                return true;
            }
        }
        return false;
    }
    
    
    /**
     * 并检测出环 入门
     *
     * @param head:
     * @return ListNode
     * @DateTime: 2023/6/10 20:10
     * @author: Coke
     */
    public static ListNode detectCycle (ListNode head) {
        ColorPrintln.greenPrintln(head);
        ListNode t = head; // 兔
        ListNode g = head; // 龟
        while (t != null && t.next != null) {
            g = g.next;
            t = t.next.next;
            if (g == t) {
                g = head;
                while (g != t) {
                    g = g.next;
                    t = t.next;
                }
                return g;
            }
        }
        return null;
    }
    
    
}
